package com.rytong.tools.ui.jsfunction;

import java.util.Timer;
import java.util.TimerTask;

import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaObject;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.LPWebView.MyLPWebView;
import com.rytong.tools.utils.Utils;

public class EmpAccelerometer implements SensorEventListener {
    final String UNKNOWN_ERROR = "1";
    final String NOT_SUPPORT_ERROR = "2";
    final String NO_DATA_ERROR = "3";

    private SensorManager sensorManager_;
    private Sensor sensor_;
    public static float accelerometerX;
    public static float accelerometerY;
    public static float accelerometerZ;
    // 记录时时的状态值
    private float xIntime_;
    private float yIntime_;
    private float zIntime_;
    // 数据返回给服务端的间隔时间
    private int stepTime_;
    private Timer timer_;
    private static boolean STOPACCELEROMETER = true;

    public void stopAccelerometer(MyLPWebView ewv, String callback) {
        if (null != timer_)
            timer_.cancel();
        timer_ = null;
        sensorManager_.unregisterListener(this);
        sensorManager_ = null;
        sensor_ = null;
        STOPACCELEROMETER = true;
        ewv.loadUrl("javascript:".concat(callback).concat("(").concat(UNKNOWN_ERROR).concat(");"));
    }

    /**
     * 服务端发过来的时间以秒为单位
     * 
     * @param time
     */
    public void setAccelerometerInterval(float time) {
        stepTime_ = (int) (time * 1000);
        if (stepTime_ < 0)
            stepTime_ = 1000;
    }

    public void startAccelerometer(MyLPWebView ewv, float interval, String Callback) {
        setAccelerometerInterval(interval);
        // 获得传感器管理器
        sensorManager_ = (SensorManager) Utils.getActivity().getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager_ != null) {
            // 获得重力传感器
            sensor_ = sensorManager_.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
        setListener(ewv, Callback);
    }

    /**
     * 为设备重力感应设置监听方法
     * 
     * @param ewv
     * 
     * @param listener
     *            监听方法(function)
     * @return
     */
    public void setListener(final MyLPWebView ewv, final String Callback) {
        if (null == sensorManager_) {
            sensorManager_ = (SensorManager) Utils.getActivity().getSystemService(Context.SENSOR_SERVICE);
        }
        if (null == timer_)
            timer_ = new Timer();

        timer_.schedule(new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    if (STOPACCELEROMETER) {
                        STOPACCELEROMETER = false;
                        synchronized (this) {
                            // 同步注册及坐标还原操作,否则无法取到修整得唯一坐标
                            if (null == sensor_) {
                                sensor_ = sensorManager_.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                            } else if (sensor_ != null) {
                                sensorManager_.registerListener(EmpAccelerometer.this, sensor_,
                                        SensorManager.SENSOR_DELAY_GAME);
                            }
                            accelerometerX = 0;
                            accelerometerY = 0;
                            accelerometerZ = 0;
                        }
                    }
                    Object[] args = new Object[1];
                    args[0] = EmpAccelerometer.this;

                    // 加载Position对象,对其附上经纬值
                    String tempString = "javascript:var Acceleration = function(x, y, z) { this._x = "
                            .concat(String.valueOf(accelerometerX))
                            .concat("; this.__defineGetter__(\"x\", function(){return this._ latitude;}); this.__defineSetter__(\"x\", function(cn){throw {message: \"Cannot modify the const attribute\"};}); this._y = ")
                            .concat(String.valueOf(accelerometerY))
                            .concat("; this.__defineGetter__(\"y\", function(){return this._ latitude;}); this.__defineSetter__(\"y\", function(cn){throw {message: \"Cannot modify the const attribute\"};}); this._z = ")
                            .concat(String.valueOf(accelerometerZ))
                            .concat("; this.__defineGetter__(\"z\", function(){return this._ latitude;}); this.__defineSetter__(\"z\", function(cn){throw {message: \"Cannot modify the const attribute\"};}); };");

                    ewv.loadUrl(tempString);
                    Utils.printOutToConsole(tempString);
                    String callbackString = "";
                    callbackString = "javascript:".concat(Callback).concat("(0,Acceleration)");
                    ewv.loadUrl(callbackString);
                    Utils.printOutToConsole(callbackString);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    ewv.loadUrl("javascript:".concat(Callback).concat("(0,null)"));
                    Utils.printException(e);
                }
            }
        }, 0, stepTime_);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // 获得x,y,z坐标
        accelerometerX = event.values[SensorManager.DATA_X] - xIntime_;
        xIntime_ = event.values[SensorManager.DATA_X];
        accelerometerY = event.values[SensorManager.DATA_Y] - yIntime_;
        yIntime_ = event.values[SensorManager.DATA_Y];
        accelerometerZ = event.values[SensorManager.DATA_Z] - zIntime_;
        zIntime_ = event.values[SensorManager.DATA_Z];
    }
}
